import { MicroAppContext } from "..";
import React, { useEffect } from "react";
import { baseName } from "../utils";
import { BrowserHistory } from "history";
import { debug } from "../utils/log";


const useActiveEntry = () => {
  const { modules } = React.useContext(MicroAppContext)
  const { routes,routeMap, basename, history } = React.useContext(MicroAppContext)
  const [route, setRoute] = React.useState<any>({});

  const activeModules = modules.filter(v => v.activeRule)
  const findActiveEntry = (routeMap: any, pathname: string, basename: string): any => {
    
    if (routeMap[location.pathname]) {
      return routeMap[location.pathname];
    }
    for (let path in routeMap) {
      const item = routeMap[path];
      const findActiveModule = activeModules.find(({ activeRule }) => activeRule(item, basename));
      if (findActiveModule) {
        
        return {
          MicroApp: findActiveModule.MicroApp,
          ...item
        }

      }
    }
    // for (let item of routes) {

    //   const findActiveModule = activeModules.find(({ activeRule }) => activeRule(item, basename));

    //   if (findActiveModule) {

    //     return {
    //       MicroApp: findActiveModule.MicroApp,
    //       ...item
    //     }

    //   }
    //   else if ((baseName(basename, item.path)) === pathname) {
    //     return item
    //   } 
    //   else if (item.children) {
    //     let activeEntry = findActiveEntry(item.children, pathname, basename);
    //     if (activeEntry) {

    //       return activeEntry
    //     }
    //   }
    // }
  }
  const matchActiveApp = () => {
    debug('matchActiveApp')
    console.time('matchActiveApp')
    let item = findActiveEntry(routeMap, window.location.pathname, basename as string)

    if (!item) {
      item = {
        name: '404',
        title: '404',
        entry: '/pages/404.js'
      }
    }

    console.timeEnd('matchActiveApp')

    setRoute({ ...item })
  }
  React.useEffect(() => {
    const unlisten = (history as BrowserHistory).listen(() => {
      matchActiveApp()
    })
    return () => {
      unlisten()
    }
  }, [])
  useEffect(() => {
    matchActiveApp()
    // let item = findActiveEntry(routes, window.location.pathname, basename as string);
    // if (!item) {
    //   item = {
    //     name: '404',
    //     entry: '/pages/404.js'
    //   }
    // }
    // setRoute({ ...item })
  }, [routes])

  return {
    route
  }
}
export default useActiveEntry